Entry Points for Plugins
In summary, entry points allow a package to open its functionalities for customization via plugins.
The package soliciting the entry points need not have any dependency or prior knowledge about the plugins implementing the entry points, and downstream users are able to compose functionality by pulling together plugins implementing the entry points.
timminsパッケージ
code:src/timmins/__init__.py
def hello_world():
print("Hello world")
Hello worldというテキストを別の方法で出力したい(例:!!! Hello world !!!)
プラグインを使う
First, let us separate the style of printing the text from the text itself.
「テキスト自身から出力形式を分離する」
code:src/timmins/__init__.py
def display(text): # controls the style of printing the text
print(text)
def hello_world(text): # calls the display() function to print the text ‘Hello world`
display("Hello world")
display関数をカスタマイズできるようにする
Let us introduce a new group of entry points named timmins.display, and expect plugin packages implementing this entry point to supply a display()-like function.
code:python
from importlib.metadata import entry_points
display_eps = entry_points(group="timmins.display")
display_eps will now be a list of EntryPoint objects, each referring to display()-like functions defined by one or more installed plugin packages.
display = display_eps[0].load()
code:src/timmins/__init__.py
from importlib.metadata import entry_points
display_eps = entry_points(group="timmins.display")
try:
display = display_eps0.load() except IndexError:
def display(text):
print(text)
def hello_world():
print("Hello world")
プラグイン timmins-plugin-fancy
code:src/timmins_plugin_fancy/__init__.py
def excl_display(text):
print("!!!", text, "!!!")
code:pyproject.toml
excl = "timmins_plugin_fancy:excl_display"
timminsとtimmins-plugin-fancyの両方をインストールしているとtimmins.hello_world()で!!!が付く
同じ関数なのにインストールしたライブラリによって挙動が変わる! すごい!
拡張側にlined_displayを追加
timminsでdisplay_eps['lined'].load()(KeyErrorを考慮する)
Or we can also load all plugins under the given group.
forで回して1つずつload
今回のケースではdisplayを上書きしてしまう
In general, we can use entry points to enable plugins to not only customize the behaviour of functions, but also of entire classes and modules.